﻿﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace newTurtle8
{
    public partial class YamamSchedule : UserControl
    {
        public static readonly string TableName = "Yamam";
        DataTable dt;
        Dictionary<string, DataRow> dict; //key==armyID, val==key's Row
        Mofa mofa;
        
        public YamamSchedule(Mofa mofa)
        {
            InitializeComponent();
            this.Dock = DockStyle.Fill;

            this.mofa = mofa;
            dict = new Dictionary<string, DataRow>();
            createTable();
            refresh();
        }
        private void createTable()
        {
            dt = new DataTable();
            dataGridView.DataSource = dt;
            
            createTableSchema();
            DataColumn[] keys = new DataColumn[1]; 
            keys[0] = dt.Columns["armyID"] ;
            dt.PrimaryKey = keys;

            initTableRows();
            checkZimunField();

            refresh();
        }
        private void createTableSchema()
        {
            int mofaDays = mofa.getTotalDays();
            DateTime firstDay = mofa.StartDate;

            dt.Columns.Add(new DataColumn("armyID", Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("firstName", Type.GetType("System.String")));
            dt.Columns.Add(new DataColumn("lastName", Type.GetType("System.String")));

            DateTime dayCounter = firstDay;

            //adding columns as the num of days in Tahasuka
            for (int i = 0; i < mofaDays; i++)
            {
                string dateHeader = dayCounter.Day.ToString() + @"/" + dayCounter.Month.ToString();
                dt.Columns.Add(new DataColumn(dateHeader, Type.GetType("System.Boolean")));

                dayCounter = dayCounter.AddDays(1);
            }
        }
        private void initTableRows()
        {
            //inserting Rows to DataTable
            SqlCommand sqlCmd = SqlManager.getSqlCommandFromFile(@"\SELECT\AlreadyCalledSoldiers.SELECT.sql");
            sqlCmd.Parameters.Add("@startDate", SqlDbType.Date).Value = mofa.StartDate;
            sqlCmd.CommandText = sqlCmd.CommandText.Replace("Table", mofa.ZimunimTableName);

            DataTable dt_temp = SqlManager.selectSqlQueryDataTable(sqlCmd);
            foreach (DataRow row in dt_temp.Rows)
	        {
                DataRow r = dt.NewRow();
                r["armyID"] = row["armyID"];
                r["firstName"] = row["firstName"];
                r["lastName"] = row["lastName"];
                dt.Rows.Add(r);
	        }
        }
        private void checkZimunField()
        {
            SqlCommand sqlCmd = SqlManager.getSqlCommandFromFile(@"\SELECT\Yamam.SELECT.sql");
            sqlCmd.Parameters.Add("@startDate", SqlDbType.Date).Value = mofa.StartDate;
            DataTable dt_temp = SqlManager.selectSqlQueryDataTable(sqlCmd);

            foreach (DataRow row in dt_temp.Rows)
            {
                DataRow temp_row = dt.Rows.Find((string)row["armyID"]);
                DateTime date = (DateTime)row["date"];
                string dateStr = date.Day.ToString() + @"/" + date.Month.ToString();
                temp_row[dateStr] = true;
            }

        }
        public void refresh()
        {
            dataGridView.DataSource = dt;

            dataGridView.Columns["firstName"].HeaderText = "שם פרטי";
            dataGridView.Columns["lastName"].HeaderText = "שם משפחה";
            dataGridView.Columns["armyID"].HeaderText = "מ.א.";

            dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;

            dataGridView.Columns["firstName"].ReadOnly = true;
            dataGridView.Columns["lastName"].ReadOnly = true;
            dataGridView.Columns["armyID"].ReadOnly = true;

            dataGridView.Columns["firstName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
            dataGridView.Columns["lastName"].AutoSizeMode = DataGridViewAutoSizeColumnMode.DisplayedCells;
            dataGridView.Columns["armyID"].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
        }

        private void setRowsCheckBox(bool isCheck, System.Collections.IEnumerable rows)
        {
            int tot_days = mofa.getTotalDays();

            foreach (DataGridViewRow row in rows)
            {
                for (int i = 0; i < tot_days; i++)
                    row.Cells[i + 3].Value = isCheck;
            }
        }

        public override string ToString()
        {
            return @"מעקב ימ''מ";
        }

        private void toolStripMenuItemMarkAll_Click(object sender, EventArgs e)
        {
            setRowsCheckBox(true, dataGridView.Rows);
        }

        private void toolStripMenuItemDemarkAll_Click(object sender, EventArgs e)
        {
            setRowsCheckBox(false, dataGridView.Rows);
        }

        private void toolStripMenuItemDemarkSelectedRows_Click(object sender, EventArgs e)
        {
            System.Collections.IEnumerable selected_rows = dataGridView.SelectedRows;
            setRowsCheckBox(false, selected_rows);
        }

        private void toolStripMenuItemMarkSelectedRows_Click(object sender, EventArgs e)
        {
            System.Collections.IEnumerable selected_rows = dataGridView.SelectedRows;
            setRowsCheckBox(true, selected_rows);
        }

        private void buttonUpdate_Click(object sender, EventArgs e)
        {
          /*  foreach (DataGridViewRow row in dataGridView.Rows)
            {
                int tot_days = mofa.getTotalDays();
                DateTime date = mofa.StartDate;

                updateCmd.Parameters["@armyID"].Value = (string)row.Cells["armyID"].Value;
                for (int i = 0; i < tot_days; i++)
                {
                    updateCmd.Parameters["@date"].Value = date;
                    updateCmd.Parameters["@isAttended"].Value = row.Cells[i + 3].Value;

                    CompanyManager.updateSqlNonQuery(updateCmd);
                    date = date.AddDays(1);
                }
            }
            */
        }

        private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            //handles only the dates columns
            if (dt.Columns[e.ColumnIndex].DataType.Equals(Type.GetType("System.Boolean")))
            {
                //retrieves the header caption. ex: "6/3"
                string hdr = (string)dt.Columns[e.ColumnIndex].Caption;
                string[] arr = hdr.Split(new char[] { '/' });
                DataRow row = dt.Rows[e.RowIndex];

                //creates the new DateTime instance to add.
                DateTime date = new DateTime(mofa.StartDate.Year, Convert.ToInt32(arr[1]), Convert.ToInt32(arr[0]));

                if (row[e.ColumnIndex] == System.DBNull.Value || !(bool)row[e.ColumnIndex])
                    Soldier.addYamam((string)row["armyID"], mofa.StartDate, date);
                else Soldier.removeYamam((string)row["armyID"], mofa.StartDate, date);
            }
        }
    }
}